import { filterObj } from '@/utils/util'
import { getAction, postAction } from '@/api/manage'
import { PAGE_MENU_TYPE } from '@/store/mutation-types'
import moment from 'moment'

export const BloodProfileMixin = {
  data() {
    return {
      chartDataLoading: false,
      chartDataSource: [],
      listDataLoading: false,
      listDataSource: [],
      statisicsDataLoading: false,
      statisicsDataSource: [],
      queryParam: {},
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      duringTime: [
        {
          value: 2,
          text: '最近两周'
        },
        {
          value: 3,
          text: '最近一个月'
        },
        {
          value: 5,
          text: '最近三个月'
        },
        {
          value: 0,
          text: '全部'
        }
      ],
      signPlan: null
    }
  },
  created() {
    if (!this.disableMixinCreated) {
      console.log(' -- mixin created -- ')
      this.loadData(0)
    }
    this.getPlan()
  },
  methods: {
    loadData(period) {
      //加载数据 加载第一页的内容
      this.ipagination.current = 1
      if (period != 'undefined') {
        this.queryParam.period = period
      }
      this.getCharts()
      this.getList()
      this.getStatisics()
    },
    getPlan() {
      getAction('/signin/plan/get', { patientId: this.$route.query[PAGE_MENU_TYPE.PatientId] }).then(res => {
        this.signPlan = res.result
      })
    },
    getQueryParams() {
      //获取查询条件
      var param = this.queryParam
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getCharts() {
      if (this.url.getCharts) {
        this.chartDataLoading = true
        var params = this.getQueryParams() //查询条件
        this.charts.axisData = []
        this.charts.seriesData = []
        postAction(this.url.getCharts, params).then(res => {
          if (res.success) {
            console.log('getCharts:', res)
            this.charts.axisData = res.result.dates || []
            this.charts.seriesData = res.result.value || []
            // 延迟500毫秒刷新统计图
            // setTimeout(() => {
            //   this.initCharts = moment.now()
            // }, 500);
            console.log('charts', this.charts)
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.chartDataLoading = false
        })
      }
    },
    getList() {
      if (this.url.getList) {
        this.listDataLoading = true
        var params = this.getQueryParams() //查询条件
        postAction(this.url.getList, params).then(res => {
          if (res.success) {
            console.log('getList:', res)
            this.listDataSource = res.result.recordList || res.result
            let lowLimit = res.result.lowLimit
            let highLimit = res.result.highLimit
            //          let lowLimit = [70,100]
            //          let highLimit = [80,110]
            //          低于:lowStatus/highStatus=3 高于:lowStatus/highStatus=1
            if (lowLimit && highLimit) {
              this.listDataSource.forEach(function(val, index, arr) {
                if (val.low < lowLimit[0]) {
                  arr[index].lowStatus = 3
                } else if (val.low > lowLimit[1]) {
                  arr[index].lowStatus = 1
                }
                if (val.high < highLimit[0]) {
                  arr[index].highStatus = 3
                } else if (val.high > highLimit[1]) {
                  arr[index].highStatus = 1
                }
              })
            }
            if (res.result.count) {
              this.ipagination.total = res.result.count
            } else {
              this.ipagination.total = 0
            }

            if (this.url.getList == '/101/02/1010202') {
              //饮食的数据特殊处理
              this.ipagination.pageSizeOptions = []
              this.formFoodData(res.result.recordList)
            }
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.listDataLoading = false
        })
      }
    },
    getStatisics() {
      if (this.url.getStatisics) {
        this.statisicsDataLoading = true
        var params = this.getQueryParams() //查询条件
        postAction(this.url.getStatisics, params).then(res => {
          if (res.success) {
            console.log('getStatisics:', res)
            this.statisicsDataSource = res.result.records || res.result
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.statisicsDataLoading = false
        })
      }
    },
    searchQueryByPagination(methodsName) {
      switch (methodsName) {
        case 'getCharts':
          this.getCharts()
          break
        case 'getStatisics':
          this.getStatisics()
          break
        case 'getList':
          this.getList()
          break
      }
    },
    handleTableChange(pagination, filters, sorter, currentDataSource, methodsName) {
      console.log(pagination)
      // //分页、排序、筛选变化时触发
      // //TODO 筛选
      // if (Object.keys(sorter).length > 0) {
      //   this.isorter.column = sorter.field;
      //   this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      // }
      this.ipagination = pagination
      if (this.url.getList == '/101/02/1010202') {
        //饮食的数据特殊处理
        this.ipagination = pagination
        this.ipagination.pageSize = 10
      }
      // console.log('syspagination', pagination)
      // console.log('pagination', this.ipagination)
      this.searchQueryByPagination(methodsName)
    },
    handleEdit: function(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    handleAdd: function() {
      if (!this.signPlan) {
        this.$message.warning('暂无打卡计划')
        return
      }
      if (new Date(this.signPlan.signInStartdate).getTime() > new Date().getTime()) {
        this.$message.warning('打卡计划未开始')
        return
      }
      this.$refs.modalForm.add({ startTime: this.signPlan.signInStartdate, endTime: this.signPlan.signInEnddate })
      this.$refs.modalForm.title = '添加'
      this.$refs.modalForm.disableSubmit = false
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.loadData(0)
      //清空列表选中
      this.onClearSelected()
    },
    formFoodData(data) {
      this.listDataSource = []
      const list = []
      data.forEach(v => {
        if (v.breakfastRecord) {
          if (v.breakfastRecord.signinRecordSuggestListInfo?.length > 0) {
            v.breakfastRecord.signinRecordSuggestListInfo.forEach((n, i) => {
              list.push({
                date: v.date,
                recordType: '早餐',
                recordTime: v.breakfastRecord.recordTime?.substr(11),
                recordPhoto: v.breakfastRecord.recordPhoto,
                remark: v.breakfastRecord.foodRecordDesc,
                recordId: v.breakfastRecord.id,
                score: n.score.split(',').reduce((a, b) => Number(a) + Number(b)),
                suggestion: {
                  suggest: n.suggest,
                  doctor: n.suggestDoctorName,
                  recordDate: n.createTime,
                  patientId: n.patientId,
                  dataId: n.dataId,
                  hasAdd: i == v.breakfastRecord.signinRecordSuggestListInfo.length - 1 ? true : false
                }
              })
            })
          } else {
            list.push({
              date: v.date,
              recordType: '早餐',
              recordTime: v.breakfastRecord.recordTime?.substr(11),
              recordPhoto: v.breakfastRecord.recordPhoto,
              remark: v.breakfastRecord.foodRecordDesc,
              recordId: v.breakfastRecord.id,
              score: '',
              suggestion: {}
            })
          }
        }
        if (v.extraBreakfast) {
          if (v.extraBreakfast.signinRecordSuggestListInfo?.length > 0) {
            v.extraBreakfast.signinRecordSuggestListInfo.forEach((n, i) => {
              list.push({
                date: v.date,
                recordType: '早餐(加)',
                recordTime: v.extraBreakfast.recordTime?.substr(11),
                recordPhoto: v.extraBreakfast.recordPhoto,
                remark: v.extraBreakfast.foodRecordDesc,
                recordId: v.extraBreakfast.id,
                score: n.score.split(',').reduce((a, b) => Number(a) + Number(b)),
                suggestion: {
                  suggest: n.suggest,
                  doctor: n.suggestDoctorName,
                  recordDate: n.createTime,
                  patientId: n.patientId,
                  dataId: n.dataId,
                  hasAdd: i == v.extraBreakfast.signinRecordSuggestListInfo.length - 1 ? true : false
                }
              })
            })
          } else {
            list.push({
              date: v.date,
              recordType: '早餐(加)',
              recordTime: v.extraBreakfast.recordTime?.substr(11),
              recordPhoto: v.extraBreakfast.recordPhoto,
              remark: v.extraBreakfast.foodRecordDesc,
              recordId: v.extraBreakfast.id,
              score: '',
              suggestion: {}
            })
          }
        }
        if (v.lunchRecord) {
          if (v.lunchRecord.signinRecordSuggestListInfo?.length > 0) {
            v.lunchRecord.signinRecordSuggestListInfo.forEach((n, i) => {
              list.push({
                date: v.date,
                recordType: '午餐',
                recordTime: v.lunchRecord.recordTime?.substr(11),
                recordPhoto: v.lunchRecord.recordPhoto,
                remark: v.lunchRecord.foodRecordDesc,
                recordId: v.lunchRecord.id,
                score: n.score.split(',').reduce((a, b) => Number(a) + Number(b)),
                suggestion: {
                  suggest: n.suggest,
                  doctor: n.suggestDoctorName,
                  recordDate: n.createTime,
                  patientId: n.patientId,
                  dataId: n.dataId,
                  hasAdd: i == v.lunchRecord.signinRecordSuggestListInfo.length - 1 ? true : false
                }
              })
            })
          } else {
            list.push({
              date: v.date,
              recordType: '午餐',
              recordTime: v.lunchRecord.recordTime?.substr(11),
              recordPhoto: v.lunchRecord.recordPhoto,
              recordId: v.lunchRecord.id,
              remark: v.lunchRecord.foodRecordDesc,
              score: '',
              suggestion: {}
            })
          }
        }
        if (v.extraLunchRecord) {
          if (v.extraLunchRecord.signinRecordSuggestListInfo?.length > 0) {
            v.extraLunchRecord.signinRecordSuggestListInfo.forEach((n, i) => {
              list.push({
                date: v.date,
                recordType: '午餐(加)',
                recordTime: v.extraLunchRecord.recordTime?.substr(11),
                recordPhoto: v.extraLunchRecord.recordPhoto,
                remark: v.extraLunchRecord.foodRecordDesc,
                recordId: v.extraLunchRecord.id,
                score: n.score.split(',').reduce((a, b) => Number(a) + Number(b)),
                suggestion: {
                  suggest: n.suggest,
                  doctor: n.suggestDoctorName,
                  recordDate: n.createTime,
                  patientId: n.patientId,
                  dataId: n.dataId,
                  hasAdd: i == v.extraLunchRecord.signinRecordSuggestListInfo.length - 1 ? true : false
                }
              })
            })
          } else {
            list.push({
              date: v.date,
              recordType: '午餐(加)',
              recordTime: v.extraLunchRecord.recordTime?.substr(11),
              recordPhoto: v.extraLunchRecord.recordPhoto,
              remark: v.extraLunchRecord.foodRecordDesc,
              recordId: v.extraLunchRecord.id,
              score: '',
              suggestion: {}
            })
          }
        }
        if (v.dinnerRecord) {
          if (v.dinnerRecord.signinRecordSuggestListInfo?.length > 0) {
            v.dinnerRecord.signinRecordSuggestListInfo.forEach((n, i) => {
              list.push({
                date: v.date,
                recordType: '晚餐',
                recordTime: v.dinnerRecord.recordTime?.substr(11),
                recordPhoto: v.dinnerRecord.recordPhoto,
                remark: v.dinnerRecord.foodRecordDesc,
                recordId: v.dinnerRecord.id,
                score: n.score.split(',').reduce((a, b) => Number(a) + Number(b)),
                suggestion: {
                  suggest: n.suggest,
                  doctor: n.suggestDoctorName,
                  recordDate: n.createTime,
                  patientId: n.patientId,
                  dataId: n.dataId,
                  hasAdd: i == v.dinnerRecord.signinRecordSuggestListInfo.length - 1 ? true : false
                }
              })
            })
          } else {
            list.push({
              date: v.date,
              recordType: '晚餐',
              recordTime: v.dinnerRecord.recordTime?.substr(11),
              recordPhoto: v.dinnerRecord.recordPhoto,
              recordId: v.dinnerRecord.id,
              remark: v.dinnerRecord.foodRecordDesc,
              score: '',
              suggestion: {}
            })
          }
        }
        if (v.extraDinnerLunchRecord) {
          if (v.extraDinnerLunchRecord.signinRecordSuggestListInfo?.length > 0) {
            v.extraDinnerLunchRecord.signinRecordSuggestListInfo.forEach((n, i) => {
              list.push({
                date: v.date,
                recordType: '晚餐(加)',
                recordTime: v.extraDinnerLunchRecord.recordTime?.substr(11),
                recordPhoto: v.extraDinnerLunchRecord.recordPhoto,
                remark: v.extraDinnerLunchRecord.foodRecordDesc,
                recordId: v.extraDinnerLunchRecord.id,
                score: n.score.split(',').reduce((a, b) => Number(a) + Number(b)),
                suggestion: {
                  suggest: n.suggest,
                  doctor: n.suggestDoctorName,
                  recordDate: n.createTime,
                  patientId: n.patientId,
                  dataId: n.dataId,
                  hasAdd: i == v.extraDinnerLunchRecord.signinRecordSuggestListInfo.length - 1 ? true : false
                }
              })
            })
          } else {
            list.push({
              date: v.date,
              recordType: '晚餐(加)',
              recordTime: v.extraDinnerLunchRecord.recordTime?.substr(11),
              recordPhoto: v.extraDinnerLunchRecord.recordPhoto,
              recordId: v.extraDinnerLunchRecord.id,
              remark: v.extraDinnerLunchRecord.foodRecordDesc,
              score: '',
              suggestion: {}
            })
          }
        }
      })
      this.listDataSource = list
      this.ipagination.total = this.ipagination.total * (list.length / 10).toFixed()
      this.ipagination.pageSize = list.length
      console.log(this.listDataSource, 'listDataSource')
    }
  }
}

